package com.ziguang.redwood.admin.controller;

import java.io.File;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.ziguang.common.SysConstant;
import com.ziguang.common.interceptor.AuthInterceptor;
import com.ziguang.redwood.admin.service.ProductTypeService;
import com.ziguang.redwood.admin.validator.ProductTypeValidator;

@ControllerBind(controllerKey = "/productType", viewPath = "/admin")
@Before(AuthInterceptor.class)
public class ProductTypeController extends Controller {
	
	private static final Logger log  = LoggerFactory.getLogger(ProductTypeController.class);
	
	/**
	 * 获取产品分类数据
	 */
	public void index(){
		List<Record> data=ProductTypeService.me.index();
		setAttr("data",data);
		render("product_category.html"); 
	}
	
	/**
	 * 前往编辑页面
	 */
	public void edit(){
		String id = this.getPara("id");
		if(id != ""){
			Record data=ProductTypeService.me.QueryEdit(id);
			setAttr("data",data);
			render("product_category_edit.html");
		}else{
			render("product_category_edit.html"); 
		}
	}
	
	/**
	 * 保存编辑页面信息
	 */
	public void save(){
		String sqlImgUrl = "";
		// 文件上传
		String RootPath = SysConstant.UPLOAD_ROOT_PATH;
		String imgRootPath = getSessionAttr(SysConstant.SESSION_INFO);
		
		String imgPath = imgRootPath + File.separator + System.currentTimeMillis();
		File file = new File(RootPath+"productType"+File.separator+imgPath);
		UploadFile img = getFile("pic",imgPath);
		if(img != null){
			if(!file.exists()){
				file.mkdirs();
			}
			String imgName = img.getFileName();
			String homeImg = RootPath+"productType"+File.separator+imgPath+File.separator+imgName;
			img.getFile().renameTo(new File(homeImg));
			sqlImgUrl = imgPath+File.separator+imgName;
		}else{
			sqlImgUrl = this.getPara("imgFix");
		}
		
		String id = this.getPara("id");
		String typeName = this.getPara("type_name");
		String sort = this.getPara("sort");
		ProductTypeService.me.save(id,typeName,sort,sqlImgUrl);
		index();
	}
	
	/**
	 * 删除当前数据
	 */
	public void delete(){
		String id = this.getPara("id");
		ProductTypeService.me.delete(id);
		renderJson("{\"code\":0}");
	}
	
}